import axios from 'axios'
import errorCode from '@/util/errorCode'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const service = axios.create({
    timeout: 10000,
    baseURL: process.env.API
})

service.interceptors.request.use(config => {
    config.headers['polymerize'] = 'polymerize ' + (config.headers || {}).polymerize
    /* get请求映射params参数 */
    if (config.method === 'get' && config.params) {
        let url = `${config.url}?`
        for (const propName of Object.keys(config.params)) {
            const value = config.params[propName]
            const part = `${encodeURIComponent(propName)}=`
            if (value !== null && typeof (value) !== 'undefined') {
                if (typeof value === 'object') {
                    for (const key of Object.keys(value)) {
                        if (value[key] !== null && typeof (value[key]) !== 'undefined') {
                            let params = `${propName}[${key}]`
                            let subPart = `${encodeURIComponent(params)}=`
                            url += `${subPart}${encodeURIComponent(value[key])}&`
                        }
                    }
                } else {
                    url += `${part}${encodeURIComponent(value)}&`
                }
            }
        }
        url = url.slice(0, -1)
        config.params = {}
        config.url = url
    }
    return config
}, error => {
    console.log(error)
    Promise.reject(error).then(r => console.error(r))
})

service.interceptors.response.use(res => {
        const code = res.data.code || 200
        const msg = errorCode[code] || res.data.msg || errorCode['default']
        if (code === 401) {

            return Promise.reject('令牌验证失败')
        } else if (code === 500) {

            return Promise.reject(new Error(msg))
        } else if (code !== 200) {

            return Promise.reject('error')
        } else if (code === 10050 || code === 10010) {

            return Promise.reject(msg)
        } else {
            if (res.data?.code === 200) {
                return res.data
            }
            return res
        }
    },
    error => {
        console.log('err' + error)
        let {message} = error
        if (message === 'Network Error') {
            message = '后端接口连接异常'
        } else if (message.includes('timeout')) {
            message = '系统接口请求超时'
        } else if (message.includes('Request failed with status code')) {
            message = '系统接口' + message.substr(message.length - 3) + '异常'
        }
        Message({
            message: message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

/* 通用下载方法 */
export function download(url, params) {
    return service.post(url, params, {
        headers: {
            'Response-Type': 'blob',
            'Content-Type': 'application/json;charset=UTF-8'
        },
        responseType: 'blob'
    }).then(res => {
        console.log(res)
        const patty = new RegExp('filename=([^;]+\\.[^.;]+);*')
            , filename = patty.exec(decodeURI(res.headers['content-disposition']))[1],
            blob = new Blob([res.data], {type: res.headers['content-type']})
        if ('download' in window.document.createElement('a')) {
            const eLink = window.document.createElement('a')
            eLink.download = filename
            eLink.style.display = 'none'
            eLink.href = URL.createObjectURL(blob)
            window.document.body.appendChild(eLink)
            eLink.click()
            URL.revokeObjectURL(eLink.href)
            window.document.body.removeChild(eLink)
        } else {
            window.navigator.msSaveBlob(blob, filename)
        }
    }).catch((r) => {
        console.error(r)
    })
}

export default service
